/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EditServiceTask.java
 *
 * Created on Mar 15, 2009, 4:20:48 PM
 */
package magis;

import edu.byu.intex2.data.Controller;
import edu.byu.intex2.data.Model;
import edu.byu.intex2.data.bo.Part;
import edu.byu.intex2.data.bo.PartServiceLine;
import edu.byu.intex2.data.bo.ServiceLine;
import edu.byu.intex2.data.bo.TaskCC;
import edu.byu.intex2.data.dao.PartDAO;
import edu.byu.intex2.data.dao.PartServiceLineDAO;
import edu.byu.intex2.data.dao.TaskCCDAO;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.plaf.basic.BasicComboBoxUI.ListDataHandler;

/**
 *
 * @author Brady
 */
public class EditServiceTask extends javax.swing.JFrame {

    private Magis magis;
    private ServiceLine sl;
    private Boolean add; // whether or not to add the sl to the service

    /** PartServiceLine List Model */
    private DefaultListModel pslListModel = new DefaultListModel();

    /** Creates new form EditServiceTask */
    public EditServiceTask(Magis magis, ServiceLine sl, Boolean add) {
        Controller.getInstance().center(this);
        initComponents();

        this.magis = magis;
        this.sl = sl;
        this.add = add;

        // Update Save Button Text based on add boolean
        if (add){
            add_btn.setText("Add Service Task");
        }else{
            add_btn.setText("Save Service Task");
        }

        // Populate JList with PartServiceLines
        populatePSLList();

        // Populate Parts Combobox
        populatePartsComboBox();

        // Update GUI
        updateGUI();
    }

    /** Update Labels and Textfields to match the sl that was passed in */
    private void updateGUI() {
        // Get Task_CC labor Hours for this task and physical car
        try {
            Double laborHours = sl.getLaborHours();
            st1_labor_txt.setText(laborHours.toString());
            calculateSubTotal(); // calculate subtotal
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Update Panel Name
        ((TitledBorder)st1_group.getBorder()).setTitle(sl.getTask().getDescription());
    }

    /** Calculate the subtotal of our serviceLine */
    private Double calculateSubTotal() {
        // Subtotal
        Double subtotal = 0.0;

        // Calc Labor Total
        Double laborTotal = Controller.roundTwoDecimals(Double.parseDouble(st1_labor_txt.getText()) * Model.HOURLY_RATE);

        // Calc Parts Total
        Double partsTotal = 0.0;
        for (PartServiceLine psl : sl.getPslList()) {
            partsTotal += psl.getQuantityUsed() * psl.getPart().getPrice(); // Qty * Price of part
        }

        partsTotal = Controller.roundTwoDecimals(partsTotal);

        // Calc Parts Tax Total
        Double partsTax = Controller.roundTwoDecimals(partsTotal * Model.TAX_RATE);

        // Calc Subtotal
        subtotal = Controller.roundTwoDecimals(laborTotal + partsTotal + partsTax);

        // Update GUI
        laborTotal_lbl.setText("$" + laborTotal.toString());
        partsTotal_lbl.setText("$" + partsTotal.toString());
        taxTotal_lbl.setText("$" + partsTax.toString());
        subtotal_lbl.setText("$" + subtotal.toString());

        // Write totals to the sl
        sl.setCostOfLabor(laborTotal);
        sl.setCostOfParts(partsTotal);

        return subtotal;
    }

    /** Populate PSL List */
    private void populatePSLList() {
        // Remove all elements
        pslListModel.removeAllElements();
        try {
            // Populate PSL List
            for (PartServiceLine psl : sl.getPslList()) {
                pslListModel.addElement(psl);
            }

            // Set the model to serviceTaskSelect_cbo
            st1_PartsJList.setModel(pslListModel);

        } catch (Exception e) {
            e.printStackTrace();
        }

        // Recalc totals
        calculateSubTotal() ;
    }

    /** Populate Parts ComboBox */
    private void populatePartsComboBox() {
        try {
            // Get our List of Parts based on the item that was selected
            List<Part> parts = PartDAO.getInstance().getByServiceFacility(ServiceController.getInstance().getService().getServiceFacilityId());

            DefaultComboBoxModel partComboModel = new DefaultComboBoxModel();

            // Populate Physical Car ComboBox
            for (Part part : parts) {
                partComboModel.addElement(part);
            }

            // Set the model to serviceTaskSelect_cbo
            st1_addPart_cmb.setModel(partComboModel);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        st1_group = new javax.swing.JPanel();
        st1_laborAndAddPartGroup = new javax.swing.JPanel();
        st1_laborGroup = new javax.swing.JPanel();
        st1_laborDispl_lbl = new javax.swing.JLabel();
        st1_labor_txt = new javax.swing.JTextField();
        st1_addPartGroup = new javax.swing.JPanel();
        st1_addPart_cmb = new javax.swing.JComboBox();
        st1_laborDisplay_lbl1 = new javax.swing.JLabel();
        st1_addPartQuantity_txt = new javax.swing.JTextField();
        st1_addPart_btn = new javax.swing.JButton();
        st1_partsAndTotalsGroup = new javax.swing.JPanel();
        st1_partsListGroup = new javax.swing.JPanel();
        st1_partsListScrollPane = new javax.swing.JScrollPane();
        st1_PartsJList = new javax.swing.JList();
        st1_removeButtonGroup = new javax.swing.JPanel();
        st1_removePart_btn = new javax.swing.JButton();
        st1_totalsGroup_pnl = new javax.swing.JPanel();
        taxTotal_lbl = new javax.swing.JLabel();
        partsTotal_lbl = new javax.swing.JLabel();
        subtotal_lbl = new javax.swing.JLabel();
        st1_partsTotalDisplay_lbl = new javax.swing.JLabel();
        st1_subtotalDisplay_lbl1 = new javax.swing.JLabel();
        st1_taxDisplay_lbl = new javax.swing.JLabel();
        laborTotal_lbl = new javax.swing.JLabel();
        st1_laborDisplay_lbl = new javax.swing.JLabel();
        menuGroup = new javax.swing.JPanel();
        cancel_btn = new javax.swing.JButton();
        add_btn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Edit Service Task");
        setMinimumSize(new java.awt.Dimension(264, 300));

        st1_group.setBorder(javax.swing.BorderFactory.createTitledBorder("Brake Job"));
        st1_group.setPreferredSize(new java.awt.Dimension(450, 180));
        st1_group.setLayout(new javax.swing.BoxLayout(st1_group, javax.swing.BoxLayout.Y_AXIS));

        st1_laborAndAddPartGroup.setMinimumSize(new java.awt.Dimension(252, 60));
        st1_laborAndAddPartGroup.setPreferredSize(new java.awt.Dimension(315, 60));
        st1_laborAndAddPartGroup.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        st1_laborGroup.setBorder(javax.swing.BorderFactory.createTitledBorder("Labor"));
        st1_laborGroup.setPreferredSize(new java.awt.Dimension(134, 55));

        st1_laborDispl_lbl.setText("Labor Hours:");
        st1_laborGroup.add(st1_laborDispl_lbl);

        st1_labor_txt.setEditable(false);
        st1_labor_txt.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        st1_labor_txt.setText("2");
        st1_labor_txt.setPreferredSize(new java.awt.Dimension(40, 20));
        st1_laborGroup.add(st1_labor_txt);

        st1_laborAndAddPartGroup.add(st1_laborGroup);

        st1_addPartGroup.setBorder(javax.swing.BorderFactory.createTitledBorder("Add Part"));

        st1_addPart_cmb.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "brake pad", "brake fluid", "transfer case", "timing belt" }));
        st1_addPartGroup.add(st1_addPart_cmb);

        st1_laborDisplay_lbl1.setText("Qty:");
        st1_addPartGroup.add(st1_laborDisplay_lbl1);

        st1_addPartQuantity_txt.setText("2");
        st1_addPartQuantity_txt.setPreferredSize(new java.awt.Dimension(20, 20));
        st1_addPartGroup.add(st1_addPartQuantity_txt);

        st1_addPart_btn.setFont(new java.awt.Font("Tahoma", 0, 8));
        st1_addPart_btn.setText("+");
        st1_addPart_btn.setMargin(new java.awt.Insets(2, 2, 2, 2));
        st1_addPart_btn.setMinimumSize(new java.awt.Dimension(20, 19));
        st1_addPart_btn.setPreferredSize(new java.awt.Dimension(25, 19));
        st1_addPart_btn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                st1_addPart_btnActionPerformed(evt);
            }
        });
        st1_addPartGroup.add(st1_addPart_btn);

        st1_laborAndAddPartGroup.add(st1_addPartGroup);

        st1_group.add(st1_laborAndAddPartGroup);

        st1_partsAndTotalsGroup.setPreferredSize(new java.awt.Dimension(426, 100));
        st1_partsAndTotalsGroup.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        st1_partsListGroup.setBorder(javax.swing.BorderFactory.createTitledBorder("Parts List"));
        st1_partsListGroup.setLayout(new javax.swing.BoxLayout(st1_partsListGroup, javax.swing.BoxLayout.Y_AXIS));

        st1_partsListScrollPane.setAutoscrolls(true);
        st1_partsListScrollPane.setMinimumSize(new java.awt.Dimension(23, 70));
        st1_partsListScrollPane.setPreferredSize(new java.awt.Dimension(200, 70));

        st1_PartsJList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        st1_PartsJList.setMinimumSize(new java.awt.Dimension(33, 45));
        st1_PartsJList.setPreferredSize(new java.awt.Dimension(100, 45));
        st1_partsListScrollPane.setViewportView(st1_PartsJList);

        st1_partsListGroup.add(st1_partsListScrollPane);

        st1_removeButtonGroup.setPreferredSize(new java.awt.Dimension(302, 25));

        st1_removePart_btn.setFont(new java.awt.Font("Tahoma", 0, 8));
        st1_removePart_btn.setText("Remove Part");
        st1_removePart_btn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                st1_removePart_btnActionPerformed(evt);
            }
        });
        st1_removeButtonGroup.add(st1_removePart_btn);

        st1_partsListGroup.add(st1_removeButtonGroup);

        st1_partsAndTotalsGroup.add(st1_partsListGroup);

        st1_totalsGroup_pnl.setLayout(new java.awt.GridBagLayout());

        taxTotal_lbl.setText("$66.75");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        st1_totalsGroup_pnl.add(taxTotal_lbl, gridBagConstraints);

        partsTotal_lbl.setText("$20.00");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0);
        st1_totalsGroup_pnl.add(partsTotal_lbl, gridBagConstraints);

        subtotal_lbl.setFont(new java.awt.Font("Tahoma", 1, 11));
        subtotal_lbl.setText("$256.75");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        st1_totalsGroup_pnl.add(subtotal_lbl, gridBagConstraints);

        st1_partsTotalDisplay_lbl.setText("Parts:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 8);
        st1_totalsGroup_pnl.add(st1_partsTotalDisplay_lbl, gridBagConstraints);

        st1_subtotalDisplay_lbl1.setText("Subtotal:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 6);
        st1_totalsGroup_pnl.add(st1_subtotalDisplay_lbl1, gridBagConstraints);

        st1_taxDisplay_lbl.setText("Tax:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 8);
        st1_totalsGroup_pnl.add(st1_taxDisplay_lbl, gridBagConstraints);

        laborTotal_lbl.setText("$66.75");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        st1_totalsGroup_pnl.add(laborTotal_lbl, gridBagConstraints);

        st1_laborDisplay_lbl.setText("Labor:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 7);
        st1_totalsGroup_pnl.add(st1_laborDisplay_lbl, gridBagConstraints);

        st1_partsAndTotalsGroup.add(st1_totalsGroup_pnl);

        st1_group.add(st1_partsAndTotalsGroup);

        getContentPane().add(st1_group, java.awt.BorderLayout.CENTER);

        menuGroup.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        cancel_btn.setFont(new java.awt.Font("Tahoma", 0, 8));
        cancel_btn.setText("Cancel");
        cancel_btn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancel_btnActionPerformed(evt);
            }
        });
        menuGroup.add(cancel_btn);

        add_btn.setFont(new java.awt.Font("Tahoma", 0, 8));
        add_btn.setText("Add Service Task");
        add_btn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                add_btnActionPerformed(evt);
            }
        });
        menuGroup.add(add_btn);

        getContentPane().add(menuGroup, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void st1_addPart_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_st1_addPart_btnActionPerformed
        // get part from combo box
        Part part = (Part) st1_addPart_cmb.getSelectedItem();

        try {
            // create a new PSL
            PartServiceLine psl = PartServiceLineDAO.getInstance().create(sl, part.getId());
            psl.setQuantityUsed(Integer.parseInt(st1_addPartQuantity_txt.getText()));

            // add psl to service line
            sl.addPslToList(psl);

            // TODO add psl to JLIST
            pslListModel.addElement(psl);

            // Refresh PSLList
            populatePSLList();
        } catch (Exception e) {
            e.printStackTrace();
        }
}//GEN-LAST:event_st1_addPart_btnActionPerformed

    private void st1_removePart_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_st1_removePart_btnActionPerformed
        sl.getPslList().remove(st1_PartsJList.getSelectedIndex());
        populatePSLList();
        calculateSubTotal();
}//GEN-LAST:event_st1_removePart_btnActionPerformed

    private void cancel_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancel_btnActionPerformed
       // close window
        this.dispose();
}//GEN-LAST:event_cancel_btnActionPerformed

    private void add_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_btnActionPerformed

        // Add service line to service
        if (add){
            Model.getInstance().getService().addServiceLine(sl);
        }

        magis.populateServiceLinesList();

        // close window
        this.dispose();
}//GEN-LAST:event_add_btnActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
//                new EditServiceTask().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton add_btn;
    private javax.swing.JButton cancel_btn;
    private javax.swing.JLabel laborTotal_lbl;
    private javax.swing.JPanel menuGroup;
    private javax.swing.JLabel partsTotal_lbl;
    private javax.swing.JList st1_PartsJList;
    private javax.swing.JPanel st1_addPartGroup;
    private javax.swing.JTextField st1_addPartQuantity_txt;
    private javax.swing.JButton st1_addPart_btn;
    private javax.swing.JComboBox st1_addPart_cmb;
    private javax.swing.JPanel st1_group;
    private javax.swing.JPanel st1_laborAndAddPartGroup;
    private javax.swing.JLabel st1_laborDispl_lbl;
    private javax.swing.JLabel st1_laborDisplay_lbl;
    private javax.swing.JLabel st1_laborDisplay_lbl1;
    private javax.swing.JPanel st1_laborGroup;
    private javax.swing.JTextField st1_labor_txt;
    private javax.swing.JPanel st1_partsAndTotalsGroup;
    private javax.swing.JPanel st1_partsListGroup;
    private javax.swing.JScrollPane st1_partsListScrollPane;
    private javax.swing.JLabel st1_partsTotalDisplay_lbl;
    private javax.swing.JPanel st1_removeButtonGroup;
    private javax.swing.JButton st1_removePart_btn;
    private javax.swing.JLabel st1_subtotalDisplay_lbl1;
    private javax.swing.JLabel st1_taxDisplay_lbl;
    private javax.swing.JPanel st1_totalsGroup_pnl;
    private javax.swing.JLabel subtotal_lbl;
    private javax.swing.JLabel taxTotal_lbl;
    // End of variables declaration//GEN-END:variables
}
